package ge.devfest.hackathon.gg;

import ge.devfest.hackathon.gg.model.Activity;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockDialogFragment;

public class SendActivityFragment extends SherlockDialogFragment {

	private static final String TAG = "SendActivityFragment";
	private static final String RETAINED_SEND_TASK_FRAGMENT = "retained_send_task_fragment";
	
	private SendActivityTask mSendActivityTask;
	private boolean mWasSent;
	
	public void beginSend(FragmentManager fm, Activity activity) {
		if (mSendActivityTask == null) {
			mSendActivityTask = new SendActivityTask(activity);
			fm.beginTransaction().add(this, RETAINED_SEND_TASK_FRAGMENT).commit();
			mSendActivityTask.execute();
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		ProgressDialog pd = new ProgressDialog(getActivity());
		pd.setMessage(getActivity().getString(R.string.sending_please_wait));
		Log.d(TAG, "created dialog");
		return pd;
	}
	
	@Override
	public void onCancel(DialogInterface dialog) {
		super.onCancel(dialog);
		if (mSendActivityTask != null) {
			mSendActivityTask.cancel(true);
		}
	}

	public boolean isInProgress() {
		return mSendActivityTask != null;
	}
	
	public boolean wasSent() {
		return mWasSent;
	}
	
	@Override
	public void onDestroyView() {
	  if (getDialog() != null && getRetainInstance()) {
		  getDialog().setDismissMessage(null);
	  }
	  super.onDestroyView();
	}
	
	private class SendActivityTask extends AsyncTask<Void, Void, Boolean> {

		private String TAG = "SendActivityTask";
		private Activity activity;
		private String url = "http://gardening.freelancer.ge/api/wine/";
//		private String url = "http://10.43.1.2:2807/api/wine/";
		
		public SendActivityTask(Activity activity) {
			this.activity = activity;
		}
		
		@Override
		protected Boolean doInBackground(Void... params) {
//			try {
//				Thread.sleep(6000);
//			} catch (InterruptedException e1) {
//				
//			}
//			if (true) {
//				return false;
//			}
			Log.d(TAG, "opening connection");
			HttpURLConnection conn = null;
			try {
				conn = (HttpURLConnection) new URL(url).openConnection();
			} catch (Exception e) {
				Log.e(TAG, "Unable to open connection to url: " + url, e);
				return false;
			}
			Log.d(TAG, "opened connection: " + conn.getURL());
			try {
				doPost(conn);
				Log.d(TAG, "succesfully posted data to remote server");
			} catch (Exception e) {
				Log.e(TAG, "Unable to post data to url: " + url, e);
				return false;
			} finally {
				if (conn != null) {
					conn.disconnect();
				}
			}
			return true;
		}
		
		private void doPost(HttpURLConnection conn) throws Exception {
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setDoOutput(true);
			ge.devfest.hackathon.gg.model.Activity.Status status = activity.getStatus();
			StringBuilder builder = new StringBuilder();
			builder.append("title=").append(activity.getTitle());
			if (status != null) {
				builder.append("&statusID=").append(status.ordinal());
			} else {
				builder.append("&statusID=").append(1);
			}
			builder.append("&latitude=").append(activity.getLatitude())
				   .append("&longitude=").append(activity.getLongitude());
			OutputStream os = null;
			try {
				Log.d(TAG, "retrieving outputStream");
				os = conn.getOutputStream();
				os.write(builder.toString().getBytes("UTF-8"));
				os.flush();
				int responseCode = conn.getResponseCode();
				String responseMessage = conn.getResponseMessage();
				Log.d(TAG, "send activity task, response code=" + responseCode + 
						   " responseMessage=" + responseMessage);
			} finally {
				if (os != null) {
					os.close();
				}
			}
		}
		
		@Override
		protected void onPostExecute(Boolean sent) {
			super.onPostExecute(sent);
			mWasSent = sent;
			if (!mWasSent) {
				Toast.makeText(getActivity(), R.string.send_activity_error_message, Toast.LENGTH_SHORT).show();
			}
			releaseTask();
			Log.d(TAG, "task done");
		}
		
		@Override
		protected void onCancelled() {
			super.onCancelled();
			releaseTask();
			Log.d(TAG, "task canceled");
		}

		private void releaseTask() {
			FragmentManager fm = getFragmentManager();
			if (fm != null) {
				SendActivityFragment f = (SendActivityFragment) fm.findFragmentByTag(RETAINED_SEND_TASK_FRAGMENT);
				if (f != null) {
					f.dismiss();
					fm.beginTransaction().remove(f).commit();
				}
			}
			mSendActivityTask = null;
			Log.v(TAG, "released sendactivity task...");
		}
	}
}
